<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          
          <el-form
            ref="listQuery"
            :inline="true"
            :model="listQuery"
            class="demo-form-inline"
          >
            <el-form-item label="广告名：">
              <el-input
                v-model="listQuery.name"
                placeholder="请输入广告名"
                type="text"
              ></el-input>
            </el-form-item>
            <el-form-item label="上架状态：">
              <el-select v-model="listQuery.is_show" placeholder="请选择" clearable filterable>
                <el-option v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
              
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchSubmit">查询</el-button>
              <el-button type="primary" @click="resetSubmit">重置</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <div class="text-right">
            <el-button type="primary" @click="handleCreate">&emsp;新增&emsp;</el-button>
        </div>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table
          ref="dataList"
          :data="menuList"
          border
          row-key="id"
          style="width:100%;margin-bottom: 20px;"
        >
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="广告素材" prop="picture">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img
                  :src="scope.row.picture"
                  alt=""
                  style="max-width: 200px;max-height: 200px"
                />
                <img
                  slot="reference"
                  :src="scope.row.picture"
                  alt=""
                  style="width: 50px;"
                />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="底部展示图" prop="bottom_img">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img
                  :src="scope.row.bottom_img"
                  alt=""
                  style="max-width: 200px;max-height: 200px"
                />
                <img
                  slot="reference"
                  :src="scope.row.bottom_img"
                  alt=""
                  style="width: 50px;"
                />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="created_at"></el-table-column>
          <el-table-column label="状态" prop="is_show">
            <template slot-scope="{row}">
              <span v-if="row.is_show === 1" class="text-green-600">显示</span>
              <span v-else class="text-red-600">隐藏</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                plain
                size="mini"
                type="primary"
                @click="handleUpdate(scope.row)"
              >编辑
              </el-button>
              <el-button
                icon="el-icon-delete"
                plain
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""
      ><em style="font-style:normal;color:red">删除后不可恢复</em
      >，你还要继续吗？</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleCloseDialog('editRulesForm')"
    >
      <el-form
        ref="editRulesForm"
        :model="editRulesForm"
        :rules="editRulesFormRules"
        class="demo-ruleForm"
        label-width="120px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="editRulesForm.name"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="广告素材" prop="picture">
          <el-upload
            :before-upload="beforeAvatarUpload"
            :http-request="customizeUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            action="#"
            class="avatar-uploader mb-4">
            <img v-if="editRulesForm.picture" :src="editRulesForm.picture" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- <el-upload
            :before-upload="beforeAvatarUpload"
            :http-request="customizeUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            action="#"
            class="upload-demo"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload> -->
        </el-form-item>
        <el-form-item label="底部展示图" prop="bottom_img">
          <el-upload
            :before-upload="beforeAvatarUpload"
            :http-request="customizeUpload"
            :on-success="handleAvatarSuccess2"
            :show-file-list="false"
            action="#"
            class="avatar-uploader mb-4">
            <img v-if="editRulesForm.bottom_img" :src="editRulesForm.bottom_img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-input
            v-model="editRulesForm.start_time"
            placeholder="请输入: undefined,"
          ></el-input>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-input
            v-model="editRulesForm.end_time"
            placeholder="请输入结束时间"
          ></el-input>
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select v-model="editRulesForm.type" placeholder="请选择" clearable filterable @change="handleChange">
            <el-option v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          
        </el-form-item>
        <el-form-item v-if="editRulesForm.type === 2" label="外部链接" prop="jump_config2">
          <el-input
            type="textarea"
            resize="none"
            :rows="5"
            v-model="editRulesForm.jump_config2"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="editRulesForm.type === 1" label="房间ID" prop="jump_config2">
          <el-input
            type="textarea"
            resize="none"
            :rows="5"
            v-model="editRulesForm.jump_config2"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="is_show">
          <el-radio-group v-model="editRulesForm.is_show">
            <el-radio :label="1">
                显示
            </el-radio>
            <el-radio :label="0">
                隐藏
            </el-radio>
          </el-radio-group>
          
        </el-form-item>

        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')"
          >提交
          </el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, listData, postAddData, putEditData } from '@/api/content/openAdvertising'

export default {
  data() {
    return {

      confirmBtn: false,
      nobilityOptions: [{ value: 8, label: '1' }],
      options2: [
        {
          value: 2,
          label: '外部链接'
        },
        {
          value: 1,
          label: '房间'
        }
      ],
      // 要修改的当前行的id
      row_id: 0,
      // 黑名单类别
      options: [
        { value: 1, label: '上架' },
        { value: 0, label: '下架' }
      ],
      // 表单规则
      editRulesFormRules: {
        name: [
          { required: true, message: '请填写标题文字1-25字符', trigger: 'blur' }
        ],
        jump_config2: [
          {required: true, message: '请输入跳转配置', trigger: 'blur'}
        ],
        picture: [{ required: true, message: '请上传图片', trigger: 'change' }],
        is_show: [{ required: true, message: '请选择状态', trigger: 'change' }],
        // start_time: [{ required: true, message: '请选择', trigger: 'change' }],
        // end_time: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      editRulesForm: {
        jump_config: undefined,
        jump_config2: undefined,
        name: undefined,
        picture: undefined,
        is_show: undefined,
        start_time: undefined,
        end_time: undefined,
        type: 2,
        bottom_img: undefined
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑广告',
        create: '添加广告'
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      listQuery: {
        page: 1,
        perPage: 10
      },
      total: 0,
      // 要删除的内容的ids
      dataIds: ''
    }
  },
  created() {
    // this.getProvince()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      for (let key in this.listQuery) {
        this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key]
      }
      listData(this.listQuery).then(response => {

        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
        this.confirmBtn = false
      })
    },
    searchSubmit() {
      this.listQuery.page = 1
      this.getList()
    },
    resetSubmit() {
      this.listQuery = {
        page: 1,
        perPage: 10
      }
      this.getList()
    },
    handleAvatarSuccess(res, file, fileList) {
      this.editRulesForm.picture = this.ossLastImgUrl
    },
    handleAvatarSuccess2(res, file, fileList) {
      this.editRulesForm.bottom_img = this.ossLastImgUrl
    },
    beforeAvatarUpload(file) {
      // const isJPG = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 10

      // if (!isJPG) {
      //   this.$message.error('上传图片只能是 JPG 格式!')
      //   return false
      // }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return false
      }
      return isLt2M
    },
    handleCloseDialog(formName) {
      this.editRulesForm = {
        jump_config: undefined,
        jump_config2: undefined,
        name: undefined,
        picture: undefined,
        is_show: undefined,
        start_time: undefined,
        end_time: undefined,
        type: 2,
        bottom_img: undefined
      }
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    },
    // 点击新增
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {
      this.row_id = row.id
      this.editRulesForm.name = row.name
      this.editRulesForm.is_show = row.is_show
      this.editRulesForm.jump_config = JSON.parse(row.jump_config)
      console.log(this.editRulesForm.jump_config)
      if(this.editRulesForm.jump_config.type === 1) {
        this.editRulesForm.type = 1
        this.editRulesForm.jump_config2 = this.editRulesForm.jump_config.id
      }else if(this.editRulesForm.jump_config.type === 2){
        this.editRulesForm.type = 2
        this.editRulesForm.jump_config2 = this.editRulesForm.jump_config.url
      }else {
        this.editRulesForm.type = undefined
        this.editRulesForm.jump_config2 = undefined
      }
      
      this.editRulesForm.picture = row.picture
      this.editRulesForm.bottom_img = row.bottom_img
    
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.editRulesForm.start_time = row.start_time
      this.editRulesForm.end_time = row.end_time
      
    },
    handleChange() {
      this.editRulesForm.jump_config2 = undefined
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.editRulesForm.type === 1) {
            this.editRulesForm.jump_config = {type: 1,id: this.editRulesForm.jump_config2}
          }else if(this.editRulesForm.type === 2){
            this.editRulesForm.jump_config = {type:2, "url": this.editRulesForm.jump_config2}
          }else {
            this.editRulesForm.jump_config = {type:0}
          }
          this.editRulesForm.jump_config = JSON.stringify(this.editRulesForm.jump_config)
          if (this.dialogStatus === 'create') {
            postAddData(this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
              }
            })
          } else {
            putEditData(this.row_id, this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          }
        } else {

          return false
        }
      })
    },
    // 点击单个删除
    handleDelete(row) {
      console.log(row)
      this.dataIds = { id: row.id }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      if (this.confirmBtn) return
      this.confirmBtn = true
      this.deleteDialogVisible = false
      deleteData(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
        }
      })
    }
  }
}
</script>

<style scoped>
[v-cloak] {
  display : none;
}

.clearfix:before,
.clearfix:after {
  display : table;
  content : "";
}

.clearfix:after {
  clear : both;
}

.box-card {
  width : 100%;
}

.avatar-uploader {
    border-radius : 6px;
    cursor        : pointer;
    position      : relative;
    overflow      : hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color : #409EFF;
  }

  .avatar-uploader-icon {
    border        : 1px dashed #d9d9d9;
    font-size   : 28px;
    color       : #8c939d;
    width       : 178px;
    height      : 178px;
    line-height : 178px;
    text-align  : center;
  }

  .avatar {
    width   : 178px;
    height  : 178px;
    display : block;
  }

</style>
